﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Data.OleDb;
using System.Data.Common;
using Public;
using DevComponents.DotNetBar.Controls;
using DevComponents.AdvTree;

namespace Check_Barcode
{
    public partial class data : DevComponents.DotNetBar.Office2007Form
    {
        public data()
        {
            InitializeComponent();
        }

        DBAccessOperater dbs = null;
        //string[] cols1 = { "ID", "机型", "设置规则", "扫描条码", "作业员", "作业时间", "校验状态", "批次号" };
        //string[] names1 = { "ID", "model", "mac1", "mac2", "CREATE_BY", "Operation_time", "iCheck_sta", "BILL_NO" };
        string[,] cell = new string[,] {
        { "ID", "ID" },{"model","机型"},{"mac1","设置规则"},{ "mac2", "扫描条码" },{ "CREATE_BY", "作业员" },{"Operation_time","作业时间"},
        {"iCheck_sta","校验状态"},{"BILL_NO","批次号"}};

        private void data_Load(object sender, EventArgs e)
        {
            //start_time.Value =DateTime.Now.a
            start_time.Value = Convert.ToDateTime(DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss"));
            end_time.Value = Convert.ToDateTime(DateTime.Now.AddDays(+1).ToString("yyyy-MM-dd HH:mm:ss"));
            //Tools.initDataView(dataGridViewX1, cols1, names1);

            Tools.initDataView2(dataGridViewX1, cell);//装载表头列标题

            //ConStr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + _DB_path;//Access数据库
            string ConStr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Application.StartupPath + @"\DB\Location.mdb";//Access数据库相对路径
            dbs = new DBAccessOperater(ConStr);
            Tools._添加DataGridViewCheckBoxColumn勾选列(dataGridViewX1); //添加勾选列
        }



        private void Btn_s_Click(object sender, EventArgs e)
        {
            string sql = "select * from data where 1=1 ";
            if (model.Text != "")
            {
                sql += " and model='" + model.Text + "' ";
            }
            if (demoSN.Text != "")
            {
                sql += " and mac2='" + demoSN.Text + "' ";
            }
            //创建日期起
            if (start_time.LockUpdateChecked == true)
            {
                sql += " AND Operation_time>=#" + start_time.Value.ToString("yyyy-MM-dd hh:mm:ss") + "# ";
            }
            //创建日期止
            if (end_time.LockUpdateChecked == true)
            {
                sql += " AND Operation_time<=#" + end_time.Value.ToString("yyyy-MM-dd hh:mm:ss") + "# ";
            }
            DataTable dt_i = dbs.SelectDataBase(sql);
            //dataGridViewX1.Columns["Operation_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            this.dataGridViewX1.DataSource = dt_i;
            //groupPanel1.Text = "数据记录   合计：" + dataGridViewX1.RowCount.ToString();

            lab_合计.Text = dataGridViewX1.RowCount.ToString();

            int _ng_qty = 0;
            int _pass_qty = 0;
            foreach (DataGridViewRow row in this.dataGridViewX1.Rows)
            {
                if (row.Cells["iCheck_sta"].Value.ToString() == "NG")
                {
                    _ng_qty = _ng_qty + 1;
                }
                if (row.Cells["iCheck_sta"].Value.ToString() == "PASS")
                {
                    _pass_qty = _pass_qty + 1;
                }
            }
            lab_ng_qty.Text = _ng_qty.ToString();
            lab_pass_qty.Text = _pass_qty.ToString();
            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
            {
                string cf = Convert.ToString(dataGridViewX1.Rows[i].Cells["iCheck_sta"].Value);
                if (cf == "PASS")//
                {
                    this.dataGridViewX1.Rows[i].Cells["iCheck_sta"].Style.BackColor = Color.LightGreen;

                }
                if (cf == "NG")//
                {
                    this.dataGridViewX1.Rows[i].Cells["iCheck_sta"].Style.BackColor = Color.OrangeRed;
                }
            }

           
        }

        private void DGV_明细_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号

        }

        private void out_excel_Click(object sender, EventArgs e)
        {
            //1 
            if (dataGridViewX1.RowCount <= 0)
            {
                MessageBox.Show("无数据，不能导出");
                return;
            }

            string saveFile, title;
            saveFileDialog1.FileName = this.Text + "" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                saveFile = saveFileDialog1.FileName;
                title = saveFileDialog1.Title;

                saveFileDialog1.Filter = "Excel文件（*.xls）|*.xls";//设置文件类型 
                saveFileDialog1.FilterIndex = 1;//设置默认文件类型显示顺序
                //ExportReport Excel_daochu = ExportReport.INSTANCE();
                //Excel_daochu.ExportExcel(DGV_明细, saveFile.ToString(), "条码数据明细");
                ExcelHelperForNPOI.TableToExcel(Tools.GetDgvToTable(dataGridViewX1), saveFile.ToString());
            }
            else { return; }

            //OleDbConnection con = new OleDbConnection();
            //try
            //{
            //    SaveFileDialog saveFile = new SaveFileDialog();
            //    saveFile.Filter = ("Excel 文件(*.xls)|*.xls");//指定文件后缀名为Excel 文件。  
            //    if (saveFile.ShowDialog() == DialogResult.OK)
            //    {
            //        string filename = saveFile.FileName;
            //        if (System.IO.File.Exists(filename))
            //        {
            //            System.IO.File.Delete(filename);//如果文件存在删除文件。  
            //        }
            //        int index = filename.LastIndexOf("//");//获取最后一个/的索引  
            //        filename = filename.Substring(index + 1);//获取excel名称(新建表的路径相对于SaveFileDialog的路径)  
            //        //select * into 建立 新的表。  
            //        //[[Excel 8.0;database= excel名].[sheet名] 如果是新建sheet表不能加$,如果向sheet里插入数据要加$.　  
            //        //sheet最多存储65535条数据。  
            //        string sql = "select top 65535 *  into   [Excel 8.0;database=" + filename + "].[用户信息] from data";
            //        con.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Application.StartupPath + "//Location.mdb";
            //        OleDbCommand com = new OleDbCommand(sql, con);
            //        con.Open();
            //        com.ExecuteNonQuery();

            //        MessageBox.Show("导出数据成功", "导出数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.ToString());
            //}
            //finally
            //{
            //    con.Close();
            //}
        }




        private void btnClearData_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除14天之前的数据吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    string sql = $@"DELETE  FROM data  WHERE Operation_time <= Date() - 14";
                    int res = dbs.ExcuteSQL(sql);
                    //int s = dbs.ExcuteSQL(strSQL);
                    if (res > 0)
                    {
                        MessageBox.Show($"操作成功！删除{res}条记录", this.Text);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作异常"+ ex.Message, this.Text);

                }
                
            }
        }
        string _now = DateTime.Now.ToString();
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int _RowIndex = this.dataGridViewX1.CurrentRow.Index;
            if (_RowIndex < 0)
            {
                return;
            }

            Frm_login fr = new Frm_login(); ;//注意：SN已经打印过！请联系品质人员确认补打
            fr.ShowDialog();

            if (fr.btn_login.DialogResult == DialogResult.OK)
            {
                if (MessageBox.Show("确认要删除吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string _ID = this.dataGridViewX1.CurrentRow.Cells[0].Value.ToString().Trim();
                    string _样板条码 = this.dataGridViewX1.CurrentRow.Cells[1].Value.ToString().Trim();
                    string _扫描条码 = this.dataGridViewX1.CurrentRow.Cells[2].Value.ToString().Trim();

                    string strSQL = "DELETE FROM data WHERE ID=" + _ID + " ";
                    int s = dbs.ExcuteSQL(strSQL);
                    if (s > 0)
                    {
                        MessageBox.Show("操作成功！", this.Text);
                        dataGridViewX1.Rows.RemoveAt(_RowIndex);//移除该行
                    }
                    else
                    {
                        MessageBox.Show("操作失败！", this.Text);
                    }
                }
            }
            else
            {
            }
        }

        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            int _RowIndex = this.dataGridViewX1.CurrentRow.Index;
            if (_RowIndex <= 0)
            {
                return;
            }

            Frm_login fr = new Frm_login(); ;//注意：SN已经打印过！请联系品质人员确认补打
            fr.ShowDialog();

            if (fr.btn_login.DialogResult == DialogResult.OK)
            {
                if (MessageBox.Show("确认要删除吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string _ID = this.dataGridViewX1.CurrentRow.Cells[0].Value.ToString().Trim();
                    string _样板条码 = this.dataGridViewX1.CurrentRow.Cells[1].Value.ToString().Trim();
                    string _扫描条码 = this.dataGridViewX1.CurrentRow.Cells[2].Value.ToString().Trim();

                    string strSQL = "DELETE FROM data WHERE MAC1='" + _样板条码 + "' ";
                    int s = dbs.ExcuteSQL(strSQL);
                    if (s >= 1)
                    {
                        MessageBox.Show("样板条码：" + _样板条码 + "删除操作成功！", this.Text);
                        Btn_s_Click(sender, e);
                        //foreach (DataGridViewRow row in this.DGV_明细.Rows)
                        //{
                        //    if (row.Cells["样板条码"].Value.ToString() == _样板条码)
                        //    {
                        //        DGV_明细.Rows.RemoveAt(row.Index);
                        //    }

                        //}
                        //DGV_明细.Rows.RemoveAt(_RowIndex);//移除该行
                    }
                    else
                    {
                        MessageBox.Show("操作失败！", this.Text);
                    }
                }
            }
            else
            {
            }
        }





        private void DGV_明细_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right)
            //{
            //    if (e.RowIndex >= 0)
            //    {
            //        //若行已是选中状态就不再进行设置
            //        if (dataGridViewX1.Rows[e.RowIndex].Selected == false)
            //        {
            //            dataGridViewX1.ClearSelection();
            //            dataGridViewX1.Rows[e.RowIndex].Selected = true;
            //        }
            //        //只选中一行时设置活动单元格
            //        if (dataGridViewX1.SelectedRows.Count == 1)
            //        {
            //            dataGridViewX1.CurrentCell = dataGridViewX1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //        }
            //        //弹出操作菜单
            //        contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
            //    }
            //}
        }

        private void model_ButtonCustomClick(object sender, EventArgs e)
        {
            string sql = $@"select model as 机型, [category] as 类别,[barcode_rule] as 条码规则, [create_time] as 创建时间
            from tbl_model_rule";
            DataTable dt = dbs.SelectDataBase(sql);
            choose_form tableFrm = new choose_form(dt, new Size(1000, 600));
            DialogResult r = tableFrm.ShowDialog();
            if (r == DialogResult.OK)
            {
                DataRow dr = tableFrm.dr;
                model.Text = dr["机型"] + "";

                //TASK_TYPE.Text = dr["工单类型"] + "";
                //context.ITEM_NO = car_model.Text = dr["车种"] + "";
                //context.ITEM_NAME = bom_no.Text = dr["BOM"] + "";
                //context.ITEM_SPEC = category.Text = dr["单品名"] + "";
                //context.SN_RULE = barcode_rule.Text = dr["条码规则"] + "";
                //T_demo.Text = dr["条码规则"] + "";
                //_条码规则 = dr["条码规则"] + "";
                //label_model.Text = $@"{model}/{category}";
            }
        }

        private void dataGridViewX1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX1.RowHeadersDefaultCellStyle.Font.Size) / 2),
                     dataGridViewX1.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                     dataGridViewX1.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX1.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }

        }

        private void dataGridViewX1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //if (e.RowIndex > -1)
            //{
            //    string Period = this.dataGridViewX1.Rows[e.RowIndex].Cells["校验状态"].Value.ToString();
            //    if (Period == "NG")
            //    {
            //        dataGridViewX1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;//整行颜色
            //        //dgvClass.Rows[e.RowIndex].Cells["开课时期"].Style.ForeColor = Color.Red;//单元格颜色  {"iCheck_sta","校验状态"},
            //    }
            //    //else if (Period == "2019年秋季班")
            //    //{
            //    //    dataGridViewX1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Blue;//FromName("#c0c0c0");
            //    //}
            //}

        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            int rus2 = 0;
            dataGridViewX1.EndEdit();//结束编辑

            //先判断有没有勾选
            int select_rows = 0;
            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
            {
                if (dataGridViewX1["check", i].Value + "" == null)
                {
                    continue;
                }
                if (dataGridViewX1.Rows[i].Cells[0].Value + "" == "1")//取选择打钩的行
                {
                    select_rows++;//选择的有
                }
            }
            if (select_rows <= 0)
            {
                Tools.ShowWaring("请勾选择要删除的行！");
            }

            DialogResult dr = MessageBoxEx.Show("确认要删除这" + select_rows.ToString() + "条记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr != DialogResult.Yes)
            {
                return;
            }

            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
            {
                if (dataGridViewX1["check", i].Value + "" == null)
                {
                    continue;
                }
                if (dataGridViewX1.Rows[i].Cells[0].Value + "" == "1")//取选择打钩的行
                {
                    long _id = Convert.ToInt64(dataGridViewX1.Rows[i].Cells["ID"].Value.ToString() + "");//选择的有
                    string sql_ii2 = $"DELETE from data where ID={_id} ";
                    rus2 += dbs.ExcuteSQL(sql_ii2);
                }
            }
            Tools.ShowWaring($"删除了{rus2}条记录！");
            Btn_s_Click(sender, e);

        }

        private void checkBoxX2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxX2.Checked)
            {
                if (dataGridViewX1.RowCount > 0)
                {
                    if (dataGridViewX1["check", 0].Value + "" == null)
                    {
                        return;
                    }

                    if (dataGridViewX1.CurrentCell == null)
                    {
                        return;
                    }
                    //string cl_name = dataGridViewX1.Columns[dataGridViewX1.CurrentCell.ColumnIndex].Name;
                    for (int i = 0; i < dataGridViewX1.RowCount; i++)
                    {
                        if (dataGridViewX1["check", i].Value + "" == "1")
                        {
                            dataGridViewX1["check", i].Value = 0;
                            continue;
                        }
                        if (dataGridViewX1.Rows[i].Visible == true)
                        {
                            dataGridViewX1["check", i].Value = 1;
                        }
                    }
                }

            }
            else
            {
                if (dataGridViewX1.RowCount > 0)
                {
                    if (dataGridViewX1["check", 0].Value + "" == null)
                    {
                        return;
                    }

                    if (dataGridViewX1.CurrentCell == null)
                    {
                        return;
                    }
                    //string cl_name = dataGridViewX1.Columns[dataGridViewX1.CurrentCell.ColumnIndex].Name;
                    for (int i = 0; i < dataGridViewX1.RowCount; i++)
                    {
                        if (dataGridViewX1["check", i].Value + "" == "1")
                        {
                            dataGridViewX1["check", i].Value = 0;
                            continue;
                        }
                        if (dataGridViewX1.Rows[i].Visible == true)
                        {
                            dataGridViewX1["check", i].Value = 1;
                        }
                    }
                }
            }
        }

        private void dataGridViewX1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            //if ("NG" == this.dataGridViewX1.Rows[e.RowIndex].Cells["校验状态"].Value.ToString())
            //{
            //    this.dataGridViewX1.Rows[e.RowIndex].Cells["校验状态"].Style.BackColor = Color.MediumPurple;
            //}
            //Application.DoEvents();

        }
    }
}
